import { getPassword, getToken, setPassword, getUserInfo } from "@/utils/auth";
import { alertMessage } from "@/utils/utils";
import { updPassword } from './change-password.service'

export default {
  name: 'change-password',
  components: {},
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.trim() == '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      passwordLogin: getPassword(),
      userInfo: getUserInfo(),
      token: getToken(),
      showDialog: false, // 是否显示弹窗
      showClose: false,
      loading: false,
      passwordType: 'password',
      passwordTypeNew: 'password',
      passwordTypeNew2: 'password',
      loginForm: {
        oldPassword: '',
        newPassword: '',
        newPassword2: ''
      },
      loginRules: {
        oldPassword: [{ required: true, trigger: 'change', validator: validatePassword }],
        newPassword: [{ required: true, trigger: 'change', validator: validatePassword }],
        newPassword2: [{ required: true, trigger: 'change', validator: validatePassword }]
      }
    }
  },
  mounted() {
    this.passwordLogin === '1' ? this.showDialog = true : this.showDialog = false;
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      })
    },

    showNewPwd() {
      if (this.passwordTypeNew === 'password') {
        this.passwordTypeNew = '';
      } else {
        this.passwordTypeNew = 'password';
      }
      this.$nextTick(() => {
        this.$refs.passwordNew.focus();
      })
    },

    showNewTwoPwd() {
      if (this.passwordTypeNew2 === 'password') {
        this.passwordTypeNew2 = '';
      } else {
        this.passwordTypeNew2 = 'password';
      }
      this.$nextTick(() => {
        this.$refs.passwordNew2.focus();
      })
    },

    handleLogin() {
      if (this.loginForm.newPassword !== this.loginForm.newPassword2) {
        alertMessage('两次密码不一致', 'warning');
        return;
      } else {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            const data = {
              newPassword: this.loginForm.newPassword,
              objectId: this.userInfo.userId,
              oldPassword: this.loginForm.oldPassword
            }
            updPassword(data).then(res => {
              alertMessage(res.message);
              setPassword(0);
              this.showDialog = false;
            })
          }
        })
      }
    }
  }
}
